package com.dreamwhale.machinery.config;


import com.alibaba.fastjson.JSONObject;
import com.dreamwhale.machinery.adviceException.DragonException;
import com.dreamwhale.machinery.utils.JwtUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

public class JWTInterceptor implements HandlerInterceptor {
    private final JwtUtils jwtUtils;

    public JWTInterceptor(JwtUtils jwtUtils) {
        this.jwtUtils = jwtUtils;
    }

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        if (!(o instanceof HandlerMethod)) {
            return true;
        }
        String token = httpServletRequest.getHeader("token");
        if (StringUtils.isBlank(token)) {
//            httpServletResponse.setCharacterEncoding("UTF-8");
//            httpServletResponse.setContentType("application/json; charset=utf-8");
//            DataResult dataResult = new DataResult(900,"请登录！",null);
//             httpServletResponse.getWriter().append(JSONObject.toJSONString(dataResult));
//            return false;

            throw new DragonException(401, "请登录");
        }
        httpServletRequest.setAttribute("userId", jwtUtils.parseJWTToken(token).get("Id"));
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
